import { getFindByParentId } from "@/api/cmn";
import { findInfoById } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";
import { useSelector } from "react-redux";

// 

const cmnSlice = createSlice({
    name:"cmn",
    initialState:{
        dictList:[]// [{id:1,children:[{id:11，children：【】}]},{id:2,children:[]},{id:3,children:[]}]
    },
    reducers:{
        upDictList(state,{payload}){
            // console.log(payload.parentId);// 父级的ID
            // 根据父级ID，查找元素
            // parentId:110000
            const info = findInfoById(state.dictList,payload.parentId);
            if(info){
                info.children = payload.dictList;
                return;
            }

            state.dictList = payload.dictList;
        }
    }
})
const {upDictList} = cmnSlice.actions;
export const getFindByParentIdSync = (parentId:number)=>{
    return async (dispatch:any)=>{
        const result:any = await getFindByParentId(parentId);
        const payload = {
            dictList:result.map((item:any)=>{
                // 如果hasChildren为true说明子项，否则无
                if(item.hasChildren) item.children = [];
                return item;
            }),
            parentId
        }
        dispatch(upDictList(payload));
    }
}
export const useCmnState = ()=>useSelector((state:any)=>state.cmn);
export default cmnSlice.reducer;